﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Algorithms
{

    public class ListNode
    {
        public int val;
        public ListNode next;
        public ListNode(int x) { val = x; }
    }
    /// <summary>
    /// 两数之和
    /// https://leetcode.com/problems/add-two-numbers/description/
    /// </summary>
    public class AddTwoNumbers
    {
        public static ListNode action1(ListNode l1, ListNode l2)
        {
            int t;
            ListNode l = new ListNode(0);
            ListNode lt = l;
            l.val = (l1.val + l2.val) % 10;
            t = (l1.val + l2.val) / 10;

            while (l1.next != null || l2.next != null)
            {

                if (l1.next != null)
                {
                    l1 = l1.next;
                    if (l2.next != null)   //都不为空
                    {
                        l2 = l2.next;
                        int value = (l1.val + l2.val + t) % 10;
                        t = (l1.val + l2.val + t) / 10;
                        lt = addNext(lt, value);
                    }
                    else
                    {                   //有一个为空
                        int value = (l1.val + t) % 10;
                        t = (l1.val + t) / 10;
                        lt = addNext(lt, value);
                    }
                }
                else
                {
                    l2 = l2.next;
                    if (l2.next != null)   //有一个不为空
                    {
                        int value = (l2.val + t) % 10;
                        t = (l2.val + t) / 10;
                        lt = addNext(lt, value);
                    }
                    else                //都为空
                    {
                        int value = (l2.val + t) % 10;
                        t = (l2.val + t) / 10;
                        lt = addNext(lt, value);

                    }
                }

            }
            if ((l1.next == null) && (l2.next == null))
            {
                if (t == 1)
                {
                    lt = addNext(lt, t);
                }

            }

            return l;

        }

        /// <summary>
        /// 添加子节点
        /// </summary>
        /// <param name="l"></param>
        /// <param name="i"></param>
        /// <returns></returns>
        public static ListNode addNext(ListNode l, int i)
        {
            l.next = new ListNode(i);
            return l.next;
        }
    }
}
